<script setup lang="ts">
  import { ref, onMounted, onUnmounted, watch } from 'vue';
  import dayjs from 'dayjs';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { getOrderApi, getCollectionApi } from '@/api/collection';
  import { Tag } from '@/components/InfoTag';
  import { jsonToSheetXlsx } from '@/components/Excel';
  import { OrderInfoModal, EditOrderModal } from './modal';
  import { useModal } from '@/components/Modal';
  import { useDrawer } from '@/components/Drawer';
  import { getOrderStatusApi } from '@/api/order';
  import { getOrderStatus, getOrderColor } from '@/utils/order';

  const rangePresets = [
    { label: '今天', value: [dayjs(), dayjs()] },
    { label: '昨天', value: [dayjs().add(-1, 'd'), dayjs()] },
    { label: '最近7天', value: [dayjs().add(-7, 'd'), dayjs()] },
    { label: '最近14天', value: [dayjs().add(-14, 'd'), dayjs()] },
    { label: '最近30天', value: [dayjs().add(-30, 'd'), dayjs()] },
    { label: '最近90天', value: [dayjs().add(-90, 'd'), dayjs()] },
  ];

  const info = ref({
    total: 0,
    allTotal: 0,
    SuccessTotalAmount: 0,
    TotalFrozenAmount: 0,
  });
  const refresh = ref(30);
  let timer: any = null;

  const [registerModal, { openDrawer }] = useDrawer();
  const [registerEditModal, { openModal: openEditModal }] = useModal();

  const [registerTable, { getRawDataSource, getDataSource, reload }] = useTable({
    title: '代收订单管理',
    canResize: true,
    columns: [
      {
        title: '序号',
        dataIndex: 'id',
      },
      {
        title: '系统单号',
        dataIndex: 'orderNo',
        resizable: true,
      },
      {
        title: '付款人姓名',
        dataIndex: 'input',
        resizable: true,
      },
      {
        title: '实付金额',
        dataIndex: 'money',
        resizable: true,
      },
      {
        title: '支付通道',
        dataIndex: 'codeTitle',
        resizable: true,
      },
      {
        title: '订单状态',
        dataIndex: 'orderStatus',
        resizable: true,
      },
      {
        title: '收款信息',
        dataIndex: 'collectionInput',
        align: 'left',
        resizable: true,
      },
      {
        title: '订单金额',
        dataIndex: 'amount',
        resizable: true,
      },
      {
        title: '验证码',
        dataIndex: 'userCode',
        resizable: true,
      },
      {
        title: '佣金/费率',
        dataIndex: 'agentRate',
        resizable: true,
      },
      {
        title: '提交时间',
        dataIndex: 'customerTime',
        resizable: true,
      },
      {
        title: '创建时间',
        dataIndex: 'create_time',
        resizable: true,
      },
      {
        title: '执行操作',
        dataIndex: 'action',
        width: 200,
        fixed: 'right',
      },
    ],
    bordered: true,
    showSelectionBar: false,
    showTableSetting: true,
    showIndexColumn: false,
    accordion: true, // 手风琴效果
    api: getOrderApi,
    fetchSetting: {
      listField: 'list',
    },
    useSearchForm: true,
    takeCare: '这是注意事项',
    formConfig: {
      labelWidth: 120,
      schemas: [
        {
          field: 'orderNo',
          label: '系统单号',
          component: 'Input',
          colProps: {
            span: 6,
          },
        },
        {
          field: 'keyword',
          label: '收款信息',
          component: 'Input',
          colProps: {
            span: 6,
          },
        },
        {
          field: 'codeTitle',
          label: '支付通道',
          component: 'ApiSelect',
          colProps: {
            span: 6,
          },
          componentProps: {
            api: getCollectionApi,
            resultField: 'list',
            labelField: 'title',
            valueField: 'title',
          },
        },
        {
          field: 'outTradeNo',
          label: '商户单号',
          component: 'Input',
          colProps: {
            span: 6,
          },
        },
        {
          field: 'payStatus',
          label: '支付状态',
          component: 'Select',
          colProps: {
            span: 6,
          },
          componentProps: {
            options: [
              {
                label: '未支付',
                value: 0,
              },
              {
                label: '已支付',
                value: 1,
              },
              {
                label: '无信息',
                value: 2,
              },
            ],
          },
        },
        {
          field: 'orderStatus',
          label: '订单状态',
          component: 'ApiSelect',
          colProps: {
            span: 6,
          },
          componentProps: {
            api: getOrderStatusApi,
            labelField: 'value',
            valueField: 'key',
          },
        },
        {
          field: 'refresh',
          label: '页面刷新时间',
          component: 'Select',
          colProps: {
            span: 6,
          },
          componentProps: {
            defaultValue: Number(localStorage.getItem('refresh')) || 30,
            options: [
              {
                label: '15秒',
                value: 15,
              },
              {
                label: '30秒',
                value: 30,
              },
              {
                label: '1分钟',
                value: 60,
              },
              {
                label: '5分钟',
                value: 300,
              },
            ],
            onChange: (value: any) => {
              refresh.value = value;
            },
          },
        },
        {
          field: 'create_time',
          label: '日期',
          component: 'RangePicker',
          colProps: {
            span: 6,
          },
          componentProps: {
            presets: rangePresets,
          },
        },
      ],
    },
    afterFetch: () => {
      const data = getRawDataSource();
      info.value = {
        ...data,
      };
    },
  });

  const exportExcel = () => {
    jsonToSheetXlsx({
      data: getDataSource(),
      filename: '新订单审核导出.xlsx',
    });
  };

  const handleInfo = (data) => {
    openDrawer(true, data);
  };

  const handleEdit = (data) => {
    openEditModal(true, { data, reload });
  };
  const refreshFunc = () => {
    reload();
    timer = setTimeout(refreshFunc, refresh.value * 1000);
  };

  const handleOk = () => {
    setTimeout(() => {
      reload();
    }, 500);
  };

  function formatInput(info) {
    let text = '';
    if (info.length <= 0) return '';
    info.forEach((element) => {
      text += element.title + ':' + element.value + '<br/>';
    });
    return text;
  }

  watch(
    () => refresh.value,
    () => {
      localStorage.setItem('refresh', refresh.value);
    },
  );
  onMounted(() => {
    timer = refreshFunc();
  });
  onMounted(() => {
    timer = setTimeout(refreshFunc, refresh.value * 1000);
    const _time = localStorage.getItem('refresh');
    if (_time) {
      refresh.value = Number(_time);
    }
  });
  onUnmounted(() => {
    clearTimeout(timer);
  });
</script>
<template>
  <main>
    <a-row :gutter="16">
      <a-col :span="24" style="margin-top: 16px">
        <BasicTable @register="registerTable">
          <template #toolbar>
            <Tag title="订单总数" color="green">{{ info.total }}</Tag>
            <Tag title="成功总额" color="green">{{ info.SuccessTotalAmount }}</Tag>
            <Tag title="接单冻结" color="green">{{ info.TotalFrozenAmount }}</Tag>
            <a-button @click="exportExcel" type="primary" size="small">筛选导出</a-button>
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'create_time'">
              {{ dayjs(record.create_time * 1000).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
            <template v-if="column.dataIndex == 'money'">
              <span style="color: #ff230f">{{ record.money }}</span>
            </template>
            <template v-if="column.key === 'customerTime'">
              {{
                record.customerTime
                  ? dayjs(record.customerTime * 1000).format('YYYY-MM-DD HH:mm:ss')
                  : ''
              }}
            </template>
            <template v-if="column.key === 'agentRate'"
              >{{ record.agentGain }}/{{ record.agentRate }}</template
            >
            <template v-if="column.dataIndex == 'collectionInput'">
              <div
                style="color: #ff230f; text-align: left"
                v-html="
                  record.collectionInput.length > 0
                    ? formatInput(record?.collectionInput)
                    : formatInput(record?.paymentInfo)
                "
              ></div>
            </template>
            <template v-if="column.key === 'orderStatus'">
              <a-tag :style="getOrderColor(record.orderStatus)">{{
                getOrderStatus(record.orderStatus)
              }}</a-tag>
            </template>
            <template v-if="column.key === 'action'">
              <TableAction
                :actions="[
                  {
                    label: '重新补单',
                    type: 'success',
                    onClick: handleEdit.bind(null, record),
                    ifShow: record.orderStatus > 1 && record.orderStatus < 6,
                  },
                  {
                    label: '订单详情',
                    type: 'primary',
                    onClick: handleInfo.bind(null, record),
                  },
                ]"
              />
            </template>
          </template>
        </BasicTable>
      </a-col>
    </a-row>

    <OrderInfoModal @register="registerModal" />
    <EditOrderModal
      @ok="handleOk"
      @register="registerEditModal"
      :showCancelBtn="false"
      :showOkBtn="false"
    />
  </main>
</template>
